class UsersController < ApplicationController

  # render new.rhtml
  def new
	@title = "Registro de Nuevo Usuario"
    @user = User.new
  end
	
  def index
	@title = "Todos los Usuarios"
	@users = User.all
	respond_to do |format|
      format.html # index.html.erb
	end
  end
  
  def show	
    @user = User.find(params[:id])
	@title = "Perfil de "+@user.name
    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @persona }
    end
  end
  
  def edit
	@title = "Editar tu perfil de usuario"
    @user = User.find(params[:id])
  end
  # POST /users
  # POST /users.xml
  
   def update
    @user = User.find(params[:id])

    respond_to do |format|
      if @user.update_attributes(params[:user])
        flash[:notice] = 'User was successfully updated.'
        format.html { redirect_to(@user) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
 
  def create
		logout_keeping_session!
		@user = User.new(params[:user])
		success = @user && @user.save
		if success && @user.errors.empty?
				# Protects against session fixation attacks, causes request forgery
		  # protection if visitor resubmits an earlier form using back
		  # button. Uncomment if you understand the tradeoffs.
		  # reset session
		  self.current_user = @user # !! now logged in
		  redirect_to :controller => "users", :action => "home", :id => current_user.id
		  flash[:notice] = "Gracias por registrarse!"
		else
		  flash[:error]  = "Oopss no pudimos crear la cuenta, por favor intenta de nuevo."
		  render :action => 'new'
		end
  end
  
    def destroy
		@user = User.find(params[:id])
		@user.destroy

		respond_to do |format|
		  format.html { redirect_to(users_url) }
		  format.xml  { head :ok }
    end
  end
  
  def home
  
		@user = User.find(current_user.id)
		@title = 'Home de ' + current_user.name + ' ' + current_user.lastname
		@friendship = Friendship.new
		@on_trips = User.find(params[:id]).on_trip
		@trips = User.find(params[:id]).trip
		friendships = User.find(params[:id]).a_users
		@friends = []
		friendships.each do |friend|
			if friend.status == 1
				@user_friend = User.find(friend.user_b_id)
				@friends << @user_friend
			end
		end
		all_users = User.all
		@available_friends = []
		
		friends = []
		friendships.each do |friend|
			if friend.status == 1 or friend.status == 2 or friend.status == 3
				@user_friend = User.find(friend.user_b_id)
				friends << @user_friend
			end
		end
		
		all_users.each do |users|
			is_friend = false
			if users.id != current_user.id
				friends.each do |friend|			
					if users.id == friend.id
						is_friend = true
					end					
				end
			else
				is_friend = true
			end
			if !is_friend
				@available_friends << users
			end
		end
		
		@pending_notifications = []
		friend_ships = friend_ships = User.find(params[:id]).a_users
		friend_ships.each do |notification|
			if notification.status == 3
				@user_friend = User.find(notification.user_b_id)
				@pending_notifications << @user_friend
			end
		end
  end 

  def notifications
		@title = "Notificaciones Pendientes"
		@pending_notifications = []
		friendships = friendships = User.find(params[:id]).a_users
		friendships.each do |notification|
			if notification.status == 3
				@user = User.find(notification.user_b_id)
				@pending_notifications << @user
			end
		end
  end
  
      # Change user passowrd
    def change_password
		@title = "Cambio de Password"
    end
    
    
    #
    # Change user passowrd
    def change_password_update
        if User.authenticate(current_user.login, params[:old_password])
            if ((params[:password] == params[:password_confirmation]) && !params[:password_confirmation].blank?)
                current_user.password_confirmation = params[:password_confirmation]
                current_user.password = params[:password]
                
                if current_user.save!
                    flash[:notice] = "Password successfully updated"
                    redirect_to change_password_path
                else
                    flash[:alert] = "Password not changed"
                    render :action => 'change_password'
                end
                 
            else
                flash[:alert] = "New Password mismatch" 
                render :action => 'change_password'
            end
        else
            flash[:alert] = "Old password incorrect" 
            render :action => 'change_password'
        end
    end
	
	def activate
		logout_keeping_session!
		user = User.find_by_activation_code(params[:activation_code]) unless params[:activation_code].blank?
		case
		when (!params[:activation_code].blank?) && user && !user.active?
		  user.activate!
		  flash[:notice] = "Signup complete! Please sign in to continue."
		  redirect_to '/login'
		when params[:activation_code].blank?
		  flash[:error] = "The activation code was missing.  Please follow the URL from your email."
		  redirect_back_or_default('/')
		else 
		  flash[:error]  = "We couldn't find a user with that activation code -- check your email? Or maybe you've already activated -- try signing in."
		  redirect_back_or_default('/')
		end
  end
  
  def forgot
	@title = "Recuperacion de Password"
    if request.post?
      user = User.find_by_email(params[:user][:email])
      if user
        user.create_reset_code
        flash[:notice] = "Reset code sent to #{user.email}"
      else
        flash[:notice] = "#{params[:user][:email]} does not exist in system"
      end
      redirect_back_or_default('/')
    end
  end
  
  def reset
	@title = "Restauracion de Password"
    @user = User.find_by_reset_code(params[:reset_code]) unless params[:reset_code].nil?
    if request.post?
      if @user.update_attributes(:password => params[:user][:password], :password_confirmation => params[:user][:password_confirmation])
        self.current_user = @user
        @user.delete_reset_code
        flash[:notice] = "Password reset successfully for #{@user.email}"
        redirect_back_or_default('/')
      else
        render :action => :reset
      end
    end
  end
  
end
